package org.enwey.icarenew.Activity;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import org.enwey.icarenew.API.APIManager;
import org.enwey.icarenew.API.RequestListResult;
import org.enwey.icarenew.API.RequestResult;
import org.enwey.icarenew.APPUtils.ToastUtil;
import org.enwey.icarenew.Activity.Base.BaseActivity;
import org.enwey.icarenew.Activity.Login.LoginActivity;
import org.enwey.icarenew.Activity.Personal.UserInfoActivity;
import org.enwey.icarenew.Adapter.MenuStyleAdapter;
import org.enwey.icarenew.Fragment.BaseFragment.BaseFragment;
import org.enwey.icarenew.Fragment.New.NewFragment;
import org.enwey.icarenew.Fragment.Topic.TopicFragment;
import org.enwey.icarenew.Manager.SettingsManager;
import org.enwey.icarenew.Model.New;
import org.enwey.icarenew.Model.NewStyle;
import org.enwey.icarenew.Model.User;
import org.enwey.icarenew.R;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends BaseActivity {
    private Toast exitToast;
    private long lastPressedBackKeyTime;
    private ImageView mMenu;
    private SlidingMenu mSlidingMenu;
    private PullToRefreshListView mMenuListView;
    private MenuStyleAdapter mMenuStyleAdapter;
    private List<NewStyle> mMenuItemList;
    private RelativeLayout mTopicNew;
    private ImageView mUserInfo;
    private User loginUser;
    private ImageView mTopicImg;
    private TextView mTopicTitle;
    private BaseFragment fragment;
    private TextView mMenuError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setUp();
        initSlidingMenu();
        findView();
        showFragment(TabPosition.Topic, null);
        registerListener();
    }

    public static enum TabPosition {
        Topic, New
    }

    private void setUp() {
        setTitle("话题新闻");
        showLeftImg();
        showRightBtn(R.drawable.ic_menu);
        mMenuStyleAdapter = new MenuStyleAdapter(this);
        mMenuItemList = new ArrayList<>();
        CallAPIGetNewStyle();
    }

    private void findView() {
        mMenu = (ImageView) this.findViewById(R.id.header_btn_right);
        mTopicNew = (RelativeLayout) this.findViewById(R.id.view_main_menu_topic);
        mUserInfo = (ImageView) this.findViewById(R.id.header_user_left);
        mTopicImg = (ImageView) this.findViewById(R.id.view_main_menu_img);
        mTopicTitle = (TextView) this.findViewById(R.id.view_main_menu_title);
        mMenuError = (TextView) this.findViewById(R.id.view_main_menu_no_data);
        mMenuListView = (PullToRefreshListView) this.findViewById(R.id.activity_main_right_list);
        mMenuListView.setAdapter(mMenuStyleAdapter);
    }

    private void initSlidingMenu() {
        mSlidingMenu = new SlidingMenu(this);
        mSlidingMenu.setMode(SlidingMenu.RIGHT);
        mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        mSlidingMenu.setShadowWidthRes(R.dimen.shadow_width);
        mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        mSlidingMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        mSlidingMenu.setMenu(R.layout.view_main_menu);
    }

    // 显示导航卡对应的fragment layout
    private void showFragment(TabPosition currentTab, String style) {
        fragment = getFragmentByPosition(currentTab);
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        if (manager.getFragments() != null) {
            for (Fragment f : manager.getFragments()) {
                transaction.hide(f);
                if (f instanceof BaseFragment) {
                    ((BaseFragment) f).hideFragment();
                }
            }
        }

        if (fragment == null) {
            if (currentTab == TabPosition.Topic) {
                fragment = new TopicFragment();
            } else if (currentTab == TabPosition.New) {
                fragment = new NewFragment();
                fragment.setStyleId(style);
            }
            transaction.add(R.id.activity_main_fragment, fragment, currentTab.toString());
        } else {
            transaction.show(fragment);
            fragment.showFragment();
        }
        transaction.commit();
    }

    private BaseFragment getFragmentByPosition(TabPosition position) {
        if (position != null) {
            BaseFragment fragment = null;
            FragmentManager manager = getSupportFragmentManager();
            String tag = position.toString();

            fragment = (BaseFragment) manager.findFragmentByTag(tag);
            return fragment;
        }
        return null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (exitToast == null) {
                exitToast = Toast.makeText(MainActivity.this, "双击退出...", Toast.LENGTH_LONG);
            }

            long delay = (exitToast.getDuration() == Toast.LENGTH_LONG ? 3500 : 2000);
            if (System.currentTimeMillis() - lastPressedBackKeyTime < delay) {
                exitToast.cancel();
                MainActivity.this.finish();
            } else {
                exitToast.show();
            }

            lastPressedBackKeyTime = System.currentTimeMillis();
        }
        return false;
    }

    private void registerListener() {
        mMenuListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                CallAPIGetNewStyle();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

            }
        });

        AdapterView.OnItemClickListener itemRegister = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                fragment.setStyleId(mMenuItemList.get(position - 1).styleid);
                showFragment(TabPosition.New, mMenuItemList.get(position - 1).styleid);
                setTitle(mMenuItemList.get(position - 1).name);
                mSlidingMenu.toggle();
                ToastUtil.show(MainActivity.this, "点击了：" + mMenuItemList.get(position - 1).styleid);
            }
        };
        mMenuListView.setOnItemClickListener(itemRegister);


        View.OnClickListener register = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (R.id.header_btn_right == v.getId()) {
                    mSlidingMenu.toggle();
                } else if (R.id.view_main_menu_topic == v.getId()) {
                    showFragment(TabPosition.Topic, null);
                    setTitle("话题新闻");
                    mSlidingMenu.toggle();
                } else if (v == mUserInfo) {
                    loginUser = SettingsManager.getLoginUser();
                    Intent intent = new Intent();
                    if (loginUser != null) {
                        intent.setClass(MainActivity.this, UserInfoActivity.class);
                    } else {
                        intent.setClass(MainActivity.this, LoginActivity.class);
                    }
                    startActivity(intent);
                }
            }
        };
        mMenu.setOnClickListener(register);
        mTopicNew.setOnClickListener(register);
        mUserInfo.setOnClickListener(register);
    }

    private void CallAPIGetNewStyle() {
        APIManager.getInstance(this).getNewStyle(null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (mMenuItemList.size() <= 0){
                    mMenuError.setVisibility(View.VISIBLE);
                }
                mMenuListView.onRefreshComplete();
            }
        }, new Response.Listener<RequestListResult<NewStyle>>() {
            @Override
            public void onResponse(RequestListResult<NewStyle> response) {
                mMenuListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                mMenuListView.onRefreshComplete();
                if (response != null) {
                    if (response.data != null) {
                        mMenuError.setVisibility(View.GONE);
                        mMenuItemList = response.data;
                        mMenuStyleAdapter.setMenuStyleList(mMenuItemList);
                        mMenuStyleAdapter.notifyDataSetChanged();
                    } else {
                        if (mMenuItemList.size() <= 0) {
                            mMenuError.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    if (mMenuItemList.size() <= 0) {
                        mMenuError.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }


}
